#include "myStateMachine.h"

#include <QFileInfo>
#include <QDebug>
#include <QSignalTransition>

StateMachine::StateMachine(Widget *widget, QObject *parent)
    : QObject(parent), pUi(widget) {
    // 初始化状态机
}

//void StateMachine::start() {
//    // 使用Widget的UI元素
//    pUi->ui->lineEdit_chainWidth->setText("StateMachine started");
//}

void StateMachine::InitMachine()
{
    // 创建状态机
    m_machine = new QStateMachine(this);

    m_resetStatus =                 new QState(m_machine);
    m_initStatus =                  new QState(m_machine);
    m_topPhotoStatus =              new QState(m_machine);
    m_AFacePhotoStatus =            new QState(m_machine);
    m_BFacePhotoStatus =            new QState(m_machine);
    m_CFacePhotoStatus =            new QState(m_machine);
    m_DFacePhotoStatus =            new QState(m_machine);
    m_bottomPhotoStatus =       new QState(m_machine);
    m_cuttingStatus =               new QState(m_machine);

    m_machine->setInitialState(m_resetStatus);// 设置初始状态

    // 添加工作流程跳转
    QSignalTransition *resetStatus_To_initStatus =                      m_resetStatus->addTransition(this, &StateMachine::toNextState, m_initStatus);
    QSignalTransition *initStatus_To_topPhotoStatus =                   m_initStatus->addTransition(this, &StateMachine::toNextState, m_topPhotoStatus);
    QSignalTransition *topPhotoStatus_To_AFacePhotoStatus =             m_topPhotoStatus->addTransition(this, &StateMachine::toNextState, m_AFacePhotoStatus);
    QSignalTransition *AFacePhotoStatus_To_BFacePhotoStatus =           m_AFacePhotoStatus->addTransition(this, &StateMachine::toNextState, m_BFacePhotoStatus);
    QSignalTransition *BFacePhotoStatus_To_CFacePhotoStatus =           m_BFacePhotoStatus->addTransition(this, &StateMachine::toNextState, m_CFacePhotoStatus);
    QSignalTransition *CFacePhotoStatus_To_DFacePhotoStatus =           m_CFacePhotoStatus->addTransition(this, &StateMachine::toNextState, m_DFacePhotoStatus);
    QSignalTransition *DFacePhotoStatus_To_m_bottomFacePhotoStatus =    m_DFacePhotoStatus->addTransition(this, &StateMachine::toNextState, m_bottomPhotoStatus);
    QSignalTransition *bottomPhotoStatus_To_cuttingStatus =             m_bottomPhotoStatus->addTransition(this, &StateMachine::toNextState, m_cuttingStatus);
    QSignalTransition *cuttingStatus_To_initStatus =                    m_cuttingStatus->addTransition(this, &StateMachine::toNextState, m_initStatus);


    // 添加复位跳转
    m_initStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);
    m_topPhotoStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);
    m_AFacePhotoStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);
    m_BFacePhotoStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);
    m_CFacePhotoStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);
    m_DFacePhotoStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);
    m_bottomPhotoStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);
    m_cuttingStatus->addTransition(this, &StateMachine::toResetStatus, m_resetStatus);


    // 连接定时器信号绑定槽函数
    initMachineConnectEnteredExited();

    // 启动状态机
    m_machine->start();
}

void StateMachine::showEntered(const QString &text)
{
    qDebug() << __FUNCTION__ << QString("%1 开始...").arg(text);
//    showLog(QString("%1 开始...").arg(text), LogType::Info);

//    setTextColor(ui->label_runStatus, QString("%1...").arg(text), StatusColor::Normal);

}

void StateMachine::showExited(const QString &text)
{
    qDebug() << __FUNCTION__ << QString("%1 完成").arg(text);
//    showLog(QString("%1 完成").arg(text), LogType::Success);

//    setTextColor(ui->label_runStatus, QString("%1").arg(text), StatusColor::Success);

}

void StateMachine::initMachineConnectEnteredExited()
{
    QString resetText = tr("复位");
    connect(m_resetStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_resetWork);
        // 显示运行状态
        showEntered(resetText);

//        showLog(resetText, LogType::Warning);
//        setTextColor(ui->label_runStatus, QString("%1...").arg(resetText), StatusColor::Normal);

    });
    connect(m_resetStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(resetText);

//        showLog("复位完成", LogType::Success);
//        setTextColor(ui->label_runStatus, QString("%1").arg("复位完成"), StatusColor::Success);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_resetWork);

//        // 开启状态机
//        m_nextStatus = true;
    });


    QString initText = tr("初始化");
    connect(m_initStatus, &QState::entered, this, [=](){

        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_initWork);
//        // 显示运行状态
        showEntered(initText);

        m_csvFlag = false;

    });
    connect(m_initStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(initText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_initWork);

    });


    QString topPhotoText = tr("顶部拍照");
    connect(m_topPhotoStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_topPhotoWork);
        // 显示运行状态
        showEntered(topPhotoText);

    });
    connect(m_topPhotoStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(topPhotoText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_topPhotoWork);

    });


    QString AFaceText = tr("A面拍照");
    connect(m_AFacePhotoStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_AFacePhotoWork);
        // 显示运行状态
        showEntered(AFaceText);

    });
    connect(m_AFacePhotoStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(AFaceText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_AFacePhotoWork);

    });


    QString BFaceText = tr("B面拍照");
    connect(m_BFacePhotoStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_BFacePhotoWork);
        // 显示运行状态
        showEntered(BFaceText);

    });
    connect(m_BFacePhotoStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(BFaceText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_BFacePhotoWork);

    });



    QString CFaceText = tr("C面拍照");
    connect(m_CFacePhotoStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_CFacePhotoWork);
        // 显示运行状态
        showEntered(CFaceText);

    });
    connect(m_CFacePhotoStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(CFaceText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_CFacePhotoWork);

    });



    QString DFaceText = tr("D面拍照");
    connect(m_DFacePhotoStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_DFacePhotoWork);
        // 显示运行状态
        showEntered(DFaceText);

    });
    connect(m_DFacePhotoStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(DFaceText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_DFacePhotoWork);

    });


    QString bottomText = tr("底部拍照");
    connect(m_bottomPhotoStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_bottomPhotoWork);
        // 显示运行状态
        showEntered(bottomText);

    });
    connect(m_bottomPhotoStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(bottomText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_bottomPhotoWork);

    });


    QString cuttingText = tr("下料");
    connect(m_cuttingStatus, &QState::entered, this, [=](){
        // 连接任务信号槽
        connect(this, &StateMachine::toStateWork, this, &StateMachine::do_cuttingWork);
        // 显示运行状态
        showEntered(cuttingText);

    });
    connect(m_cuttingStatus, &QState::exited, this, [=](){
        // 显示运行状态
        showExited(cuttingText);

        // 断开任务信号槽
        disconnect(this, &StateMachine::toStateWork, this, &StateMachine::do_cuttingWork);
    });
}

void StateMachine::do_initWork()
{
    QString fileName;

    if(false == m_csvFlag)
    {
        if(!getCsvFile(fileName))
        {
            return;
        }
    }

//    int time = ui->le_initTime->text().toInt();

    if(conutDelay())
    {
        m_csvFlag = false;
        emit toNextState();
    }
}

void StateMachine::do_topPhotoWork()
{
//    int time = ui->le_topPhotoTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_AFacePhotoWork()
{
//    int time = ui->le_AFacePhotoTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_BFacePhotoWork()
{
//    int time = ui->le_BFacePhotoTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_CFacePhotoWork()
{
//    int time = ui->le_CFacePhotoTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_DFacePhotoWork()
{
//    int time = ui->le_DFacePhotoTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_bottomPhotoWork()
{
//    int time = ui->le_bottomPhotoTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_cuttingWork()
{
//    int time = ui->le_cuttingTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_resetWork()
{
//    int time = ui->le_resetTime->text().toInt();
    int time = 3;

    if(conutDelay(time))
    {
        emit toNextState();
    }
}

void StateMachine::do_clearAllFlag()
{
    // 清理所有标志位

}

bool StateMachine::conutDelay(int delayTime)
{
    static int conutTime = 0;

    ++conutTime;

    conutTime %= delayTime;

    QString text = QString("计时：%1s / %2s").arg(conutTime).arg(delayTime);

    qDebug() << text;

//    showLog(text, LogType::Info);
//    setTextColor(ui->label_countDown, QString::number(delayTime - conutTime), StatusColor::Normal);

    if(0 == conutTime)
    {
        return true;
    }

    return false;
}


bool StateMachine::getCsvFile(const QString &csvPath)
{


    // 检查CSV文件是否存在
    if (!isExitsScvFile(csvPath))
    {
        return false;
    }

    // 读取文件
    QList<QMap<QString, QVariant>> csvDataList = readCsvFile(csvPath);
    if(csvDataList.isEmpty())
    {
//        showLog("没有读到数据", LogType::Error);
        return false;
    }

    // 解析
    QString productCode = getDataByRowAndColumn(csvDataList, 0, "产品代号");

//    if(productCode.isEmpty())
//    {

//    }

//    showLog(QString("获取到任务-->产品码：%1").arg(productCode), LogType::Info);


    // 删除文件
    if(QFile::remove(csvPath))
    {
//        showLog(QString("CSV文件删除"), LogType::Success);

        m_csvFlag = true;

    } else {
//        showLog(QString("CSV文件删除失败！"), LogType::Error);
        return false;
    }

    return true;
}


bool StateMachine::isExitsScvFile(const QString &csvPath)
{
    QFileInfo iniFile(csvPath);

    // 检查CSV文件是否存在
    if (!iniFile.exists())
    {
//        showLog(QString("CSV文件不存在：%1").arg(csvPath), LogType::Error);
        return false;
    }
    return true;
}


QList<QMap<QString, QVariant>> StateMachine::readCsvFile(const QString &csvPath) {
    QList<QMap<QString, QVariant>> csvDataList;
//    QDir dir(path);
//    QStringList filters;
//    filters << "*.csv";
//    dir.setNameFilters(filters);

//    // 获取文件列表
//    QStringList csvFiles = dir.entryList();
//    if (csvFiles.isEmpty()) {
//        qDebug() << "没有找到任何.csv文件";
//        return csvDataList;
//    }

    // 检查csv文件是否存在
    if(!isExitsScvFile(csvPath))
    {
        return csvDataList;
    }

    // 读取csv文件的内容
    QString filePath = csvPath;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件：" << filePath;
        return csvDataList;
    }

    QTextStream in(&file);
    QStringList headers;
    bool isHeader = true;
    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList values = line.split(',');

        if (isHeader) {
            headers = values;
            isHeader = false;
        } else {
            QMap<QString, QVariant> rowData;
            for (int i = 0; i < headers.size(); ++i) {
                rowData[headers.at(i)] = values.at(i);
            }
            csvDataList.append(rowData);
        }
    }
    file.close();

//    // 删除文件
//    if (QFile::remove(filePath)) {
//        qDebug() << "文件已删除：" << filePath;
//    } else {
//        qDebug() << "无法删除文件：" << filePath;
//    }

    return csvDataList;
}


QString StateMachine::getDataByRowAndColumn(const QList<QMap<QString, QVariant>> &csvDataList, int row, const QString &column) {
    if (row >= 0 && row < csvDataList.size()) {
        const QMap<QString, QVariant> &rowData = csvDataList.at(row);
        if (rowData.contains(column)) {
            return rowData.value(column).toString();
        } else {
            qDebug() << "列名不存在：" << column;
        }
    } else {
        qDebug() << "行号超出范围：" << row;
    }
    return QString();
}

QMap<QString, QVariant> StateMachine::getRowData(const QList<QMap<QString, QVariant>> &csvDataList, int row) {
    if (row >= 0 && row < csvDataList.size()) {
        return csvDataList.at(row);
    } else {
        qDebug() << "行号超出范围：" << row;
        return QMap<QString, QVariant>();
    }
}
